#include "../LOG_true/toplog.h"
#include "../LOG_true/sink.hpp"

enum TIMEGAP
{
    SECOND,
    MINUTE,
    HOUR,
    DAY
};

// 时间滚动
class RollTimeSink : public TopLog::Logsink
{
public:
    RollTimeSink(const string &basename, TIMEGAP gap_type) : _basename(basename)
    {
        switch (gap_type)
        {
        case TIMEGAP::SECOND:
            _gapszie = 1;
            break;
        case TIMEGAP::MINUTE:
            _gapszie = 60;
            break;
        case TIMEGAP::HOUR:
            _gapszie = 3600;
            break;
        case TIMEGAP::DAY:
            _gapszie = 3600 * 24;
            break;
        }
        //
        _cur_gap = _gapszie == 1 ? TopLog::Unil::Data::Gettime() : TopLog::Unil::Data::Gettime() % _gapszie; // 获取当前时间是第几个时间段  %1==0
        std::string filename = createNewFile();                                                              // 创建文件
        // 创建目录
        TopLog::Unil::File::CreateDirectory(TopLog::Unil::File::Path(filename));
        // 创建并打开日志文件
        _oft.open(filename, std::ios::binary | std::ios::app);
        assert(_oft.is_open());
    };

    // 将日志消息写入标准输出
    void log(const char *data, size_t len)
    {
        time_t cur = TopLog::Unil::Data::Gettime();
        if ((cur % _gapszie) != _cur_gap) // 3600 %60 ==0
        {
            _oft.close();
            std::string filename = createNewFile();
            _oft.open(filename, std::ios::binary | std::ios::app);
            assert(_oft.is_open());
        }

        _oft.write(data, len);
        assert(_oft.good());
    };

private:
    string createNewFile()
    {
        time_t t = TopLog::Unil::Data::Gettime();
        struct tm lt;
        localtime_r(&t, &lt); // 时间转换 时间戳->结构体
        stringstream filename;
        filename << _basename;
        filename << lt.tm_year + 1900;
        filename << lt.tm_mon + 1;
        filename << lt.tm_mday;
        filename << lt.tm_hour;
        filename << lt.tm_min;
        filename << lt.tm_sec;
        filename << ".log";

        return filename.str();
    };
    std::string _basename;
    std::ofstream _oft;
    std::size_t _gapszie;
    std::size_t _cur_gap;
};

int main()
{

    std::unique_ptr<TopLog::LoggerBuilder> builder(new TopLog::GloBalLoggerBuilder()); // 智能指针管理对象
    builder->buildLoggerType(TopLog::LoggerType::LOGGER_SYNC);
    builder->buildLoggerLevel(TopLog::Logs::Value::UNKNOWNS);
    builder->buildLoggerName("asnyc_logger");
    builder->buildLoggerFamtter("%m%n");
    builder->buildSink<TopLog::StdoutSink>();
    builder->buildSink<TopLog::FileSink>("./logs/snync.log");
    builder->buildSink<RollTimeSink>("./logs/roll_by_snync_time.log",TIMEGAP::SECOND);
    TopLog::Logger::ptr logger= builder->build();
    size_t cur = TopLog::Unil::Data::Gettime();
    while (cur + 5 > TopLog::Unil::Data::Gettime())
    {
        logger->debug("%s","日志测试");
    }

    return 0;
}